package com.silver.weibo.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.silver.weibo.entity.Users;
import com.silver.weibo.server.Impl.UserServiceImpl;
import com.silver.weibo.server.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("uds")
public class MyUserDetailsService implements UserDetailsService {

    private UserService userService;
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    public void setPasswordEncoder(BCryptPasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        List<GrantedAuthority> list = AuthorityUtils.commaSeparatedStringToAuthorityList("public");

        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("user_loginname",s);
        wrapper.select("user_loginname","user_password");

        Users one = userService.getOne(wrapper);
        if (one == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        return new User(one.getUserLoginname(),passwordEncoder.encode(one.getUserPassword()),list);
    }
}
